package com.xm.util;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.xm.pojo.Sysuser;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

@Component("mobileFilter")
public class MobileFilter implements Filter {
    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(MobileFilter.class);
    protected FilterConfig filterConfig;

    @Resource(name = "ehcacheCacheProvider")
    private EhcacheCacheProvider cacheProvider;

    public void destroy() {
        filterConfig = null;
    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {

        HttpServletRequest req = (HttpServletRequest) arg0;
        String uri = req.getRequestURI();
        String realUri = uri.replace(req.getContextPath().toString(),"");
        String token =req.getParameter("token");
        if (isAuth(realUri)) {
            Sysuser sysuser=(Sysuser)cacheProvider.get(token);
            if (sysuser == null) {
                    loginPath(arg0, arg1, arg2);
            } else {
                commonPath(arg0, arg1, arg2);
            }
        } else {
            commonPath(arg0, arg1, arg2);
        }
    }

    public void loginPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {
        JSONMsg jsonMsg = new JSONMsg();
        jsonMsg.setStatus(false);
        jsonMsg.setMsg("tonken失效，请重新登陆");
        ObjectMapper mapper = new ObjectMapper();
        String rs="";
        try {
            rs= mapper.writeValueAsString(jsonMsg);
        }catch (Exception e){
            logger.error(e.toString());
        }
        arg1.setCharacterEncoding("UTF-8");
        arg1.setContentType("application/json; charset=utf-8");
        try {
            PrintWriter out = arg1.getWriter();
            out.write(rs);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断URL是否需要被过滤
     * 2016-8-2下午7:28:06
     * zhuangjf
     */
    public boolean isAuth(String realUri) {
        boolean noAuth=!realUri.matches("(/rest|rest)/m/login|(/rest|rest)/m/register");
        return noAuth;
    }

    public void commonPath(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) {
        try {
            arg2.doFilter(arg0, arg1);
        } catch (IOException e) {
            logger.error(e.toString());
        } catch (ServletException e) {
            logger.error(e.toString());
        }
        return;
    }
    public void init(FilterConfig fConfig) throws ServletException {filterConfig = fConfig;}
}
